package com.summer.campussct.exception;

import cn.hutool.core.util.StrUtil;
import com.summer.campussct.pojo.dto.RestResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 捕获validation框架的参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestResult catchMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<String> msgList = new ArrayList<>();

        bindingResult.getFieldErrors().forEach(item -> msgList.add(item.getDefaultMessage()));

        // 拼接错误信息
        String msg = StrUtil.join( ",", msgList);
        return RestResult.error(msg);
    }
}
